def check(lines, name):
  for line in lines:
    print(line)
    if line.find(name) >= 0:
      return True
  return False

# need a backup for safety

def add_test(name):
  header = 'include/test_album.h' 
  f = open(header, 'r')
  lines = f.readlines()
  f.close()
  if check(lines, name):
    print('test %s already exists' % name)
    return

  # create new test
  anchor = '//anchor\n'
  new_test = """
class $NAME$ : public Test {
public:
  $NAME$() : Test("$NAME$") { }
  void Run(int argc, char *argv[]);
};
$ANCHOR$ """
  new_test = new_test.replace('$ANCHOR$', anchor)
  new_test = new_test.replace('$NAME$', name)
  print(new_test)

  # add new_test declaration to header file
  f = open(header, 'w')
  for line in lines:
    line = line.replace(anchor, new_test)
    f.write(line)
  f.close()

  reg = 'src/test.cc'
  f = open(reg, 'r')
  lines = f.readlines()
  f.close()

  reg_code = """this->AddTest(new $NAME$());
  $ANCHOR$"""
  reg_code = reg_code.replace('$ANCHOR$', anchor)
  reg_code = reg_code.replace('$NAME$', name)

  f = open(reg, 'w')
  for line in lines:
    line = line.replace(anchor, reg_code)
    f.write(line)
  f.close()

  def_code = """
#include "test_album.h"
namespace ct {
void $NAME$::Run(int argc, char *argv[]) {
}
} // ct
"""
  def_code = def_code.replace('$NAME$', name)
  src = 'src/' + name + '.cc'
  f = open(src, 'w')
  f.write(def_code)
  f.close()

if __name__ == "__main__":
  import sys
  if len(sys.argv) != 2:
    print("Usage: add_test.py [test_name]")
  else:
    name = sys.argv[1]
    add_test(name)

